

let util = {
    /**
     * 安全设置变量，如果路径有缺失，会自动创建
     * 用法：
     * mset(() = Memory.Somepath.SomeFolder.Somekey,"SomeValue");
     */
    mset:function(fn,value = null){
        let path;
        if(fn instanceof Function){
            fn = fn.toString().replace('() => ','');
            fn = fn.replace(/\s+/g,"");
            path = fn.split(".");
        }else if(fn.constructor.name == "String"){
            path = fn.split(".");
        }
        let before;
        let root = global;
        let rootName;
        for(let node of path){
            if(root[node] == undefined){
                root[node] = {};
            }
            before = root;
            root = root[node];
            rootName = node;
        }

        before[rootName] = value;
    },
    /**
     * 用法：
     * mget(()=> Memory.somepath.someinternalPath.somekey,"123")
     * 获取 Memory.somepath.someinternalPath.somekey 上的值，如果没有获取到返回默认值123
     */
    mget:function(fn,defValue){
        if(fn instanceof Function){
            try{
                return fn() || defValue;
            }catch(e){
                return defValue;
            }
        }else if(fn.constructor.name == "String"){
            let path = fn.split(".");
            let root = global;
            for(let dom of path){
                if(root[dom] == undefined){
                    return defValue;
                }else{
                    root = root[dom]; 
                }
            }

            return root;
        }
    },
    //批量设置 Prototype
    setPrototype:function(source,obj){
        for(let name in obj){
            source.prototype[name] = obj[name];
        }
    },
    isString:function(str){
        if(str == undefined){
            return false;
        }
        if(str.constructor.name == "String"){
            return true;
        }
        return false;
    },
    getRoomDistanceByName:function(n1,n2){
        let p1 = util.getRoomFormatPositionByName(n1);
        let p2 = util.getRoomFormatPositionByName(n2);

        let dx = Math.abs(p1.x-p2.x);
        let dy = Math.abs(p1.y-p2.y);

        let d = Math.sqrt(dx*dx+dy*dy);

        return d;
    },
    /**
     * 返回以东北为正的房间坐标，例如
     * E5S6 => 5,6
     * W6S7 => -7,7
     */
    getRoomFormatPositionByName:function(name){//EW**SN** 
        let p = name.replace(/^[EW]{1}/g,"").replace(/[SN]{1}/g,",").split(",");//String array
        let pos = {
            x:Number(p[0]),
            y:Number(p[1])
        }
        //判断x坐标是否是负数
        if(name.indexOf("W") != -1){//坐标在西方向
            pos.x = -pos.x-1;
        }
        if(name.indexOf("N") != -1){
            pos.y = -pos.y-1;
        }

        return pos;
    },
    isRoomName(str){
        return /[EW][0-9]+[NS][0-9]+/g.test(str);
    },
    mapToArray(collection,fn){
        let temp = [];
        let seter = function(value){
            temp.push(value);
        }
        for(let key in collection){
            let value = collection[key];
            fn(seter,key,value);
        }
        return temp;
    },
    mapToObj(collection,fn){
        let temp = {};

        let seter = function(key,value){
            temp[key] = value;
        }
        for(let key in collection){
            let value = collection[key];
            fn(seter,key,value);
        }

        return temp;
    },
    filterObject(obj,f){
        let buffer = {};
        for(let k in obj){
            let v = obj[k];
            if(f(k,v)){
                buffer[k] = v;
            }
        }
        return buffer;
    },
    filterArray(arr,f){
        let buffer = [];
        for(let v of arr){
            if(f(v)){
                buffer.push(v);
            }
        }
        return buffer;
    },
    classifyArray(array,filters){

        // util.classifyArray([],{
        //     c1:function(i){//全部过一遍
        //          return true;
        //     },
        //     c2:function(i){
        //          return true;
        //     }
        // })

        let un = array;
        let ed = {};
        for(let name in filters){
            ed[name] = [];
        }

        while(un.length > 0){
            let item = un.shift();
            for(let name in filters){//按顺序去测试
                if(filters[name](item)){
                    ed[name].push(item);
                    break;//分类完成
                }
            }
        }
        
        return ed;
    },
    zipBody(array){
        let buffer = {};
        for(let i of array){
            if(buffer[i] == undefined){
                buffer[i] = 1;
            }else{
                buffer[i]++;
            }
        }
        return buffer;
    },
    unzipBody(obj){
        let buffer = [];
        for(let type in obj){
            for(let i = 0;i < obj[type];i++){
                buffer.push(type);
            }
        }
        return buffer;
    },
    log(content,style = {

    }){
        //formatStyle
        let stylebuffer = "";
        for(let name in style){
            stylebuffer += `${name}:${style[name]};`
        }
        console.log(`<span style="${stylebuffer}">${content}</span>`);
    },
    //生成随机整数[minNum,maxNum]
    randomNum(minNum,maxNum){ 
        switch(arguments.length){ 
            case 1: 
                return parseInt(Math.random()*minNum+1,10); 
            case 2: 
                return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
                default: 
                    return 0; 
        } 
    },
    randomArray(target){
        return target[util.randomNum(0,target.length-1)];
    },
    analysisData(array,fn){
        let buffer = [];

        if(array.constructor.name == "Array"){
            for(let i of array){
                let result = fn(i);
                buffer.push(result);
            }
        }else if(array.constructor.name == "Object"){
            for(let key in array){
                let result = fn(key,array[key]);
                buffer.push(result);
            }
        }
        return buffer;
    }
}

let COLOR = {
    GREEN:"#4CAF50",
    RED:"#F44336",
    YELLOW:"#FFC107",
    
}

module.exports.Util = util;
module.exports.COLOR = COLOR;